package sf.jooq;

import org.jooq.Record;
import sf.core.DBObject;
import sf.database.dao.DBContext;
import sf.database.dialect.DBDialect;
import sf.database.meta.MetaHolder;
import sf.database.meta.TableMapping;
import sf.jooq.tables.JooqTable;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class JooqTables {
    private static Map<Class, JooqTable> tableMap = new ConcurrentHashMap<>();

    /**
     * @param clz
     * @param <T>
     * @return
     */
    public static <T extends DBObject> JooqTable<?> getTable(Class<T> clz) {
        return getTable(null, clz);
    }

    /**
     * @param clz
     * @param <T>
     * @return
     */
    public static <T extends DBObject> JooqTable<?> getTable(DBContext context, Class<T> clz) {
        return getTable(context, clz, null);
    }

    /**
     * @param clz
     * @param dialect
     * @param <T>
     * @return
     */
    public static <T extends DBObject> JooqTable<?> getTable(DBContext context, Class<T> clz, DBDialect dialect) {
        TableMapping tm = MetaHolder.getMeta(clz);
        JooqTable<?> pb = getTable(context, tm, dialect);
        return pb;
    }

    /**
     * @param tm
     * @param <T>
     * @return
     */
    public static <T extends DBObject> JooqTable<?> getTable(DBContext context, TableMapping tm) {
        return getTable(context, tm, null);
    }

    /**
     * @param tm
     * @param dialect
     * @param <T>
     * @return
     */
    public static <T extends DBObject> JooqTable<?> getTable(DBContext context, TableMapping tm, DBDialect dialect) {
        JooqTable<?> pb = tableMap.get(tm.getThisType());
        if (pb == null) {
            pb = new JooqTable(context, tm.getThisType(), dialect);
            tableMap.put(tm.getThisType(), pb);
        }
        return pb;
    }
}
